<template>
  <div class="container max-w-6xl p-4 bg-white bg-opacity-60 my-4 rounded-lg backdrop-blur-md">
    <!-- 字典选择 -->
    <div class="flex space-x-4 my-4">
      <!-- 作品风格 -->
      <span class="p-float-label">
        <CascadeSelect
          v-model="w_style"
          :options="_w_style"
          option-group-label="value"
          option-label="value"
          option-value="did"
          :optionGroupChildren="['children']"
          :class="{ 'p-invalid': commit && !w_style }"
        />
        <label>选择作品风格</label>
      </span>

      <!--作品面料 -->
      <span class="p-float-label">
        <CascadeSelect
          v-model="w_material"
          :options="_w_material"
          option-group-label="value"
          option-label="value"
          option-value="did"
          :optionGroupChildren="['children']"
          :class="{ 'p-invalid': commit && !w_material }"
        />
        <label>选择作品面料</label>
      </span>

      <!-- 作品服装类型 -->
      <span class="p-float-label">
        <CascadeSelect
          v-model="w_clothes"
          :options="_w_clothes"
          option-group-label="value"
          option-label="value"
          option-value="did"
          :optionGroupChildren="['children']"
          :class="{ 'p-invalid': commit && !w_clothes }"
        />
        <label>选择服装类型</label>
      </span>
    </div>

    <!-- 图片上传 -->
    <div class="mb-4">
      <FileUpload
        name="demo[]"
        @select="onSelect"
        accept="image/*"
        :maxFileSize="2000000"
        :fileLimit="5"
        chooseLabel="添加作品图"
        :show-upload-button="false"
        :show-cancel-button="false"
      >
        <template #empty>
          <p>拖放图片到这里上传</p>
        </template>
      </FileUpload>
    </div>

    <!-- 内容编辑器 -->
    <Editor ref="editor" v-model="content" editorStyle="height: 320px">
      <template #toolbar>
        <span class="ql-formats">
          <select class="ql-header" defaultValue="0">
            <option value="1">大标题</option>
            <option value="2">小标题</option>
            <option value="0">正文</option>
          </select>
          <select class="ql-font">
            <option></option>
            <option value="serif"></option>
            <option value="monospace"></option>
          </select>
        </span>
        <span class="ql-formats">
          <button class="ql-bold" type="button" v-tooltip.bottom="'加粗'"></button>
          <button class="ql-italic" type="button" v-tooltip.bottom="'斜体'"></button>
          <button class="ql-underline" type="button" v-tooltip.bottom="'下划线'"></button>
        </span>
        <span class="ql-formats">
          <span class="ql-formats" v-tooltip.bottom="'颜色'">
            <select class="ql-color"></select>
          </span>
          <span class="ql-formats" v-tooltip.bottom="'背景色'">
            <select class="ql-background" v-tooltip.bottom="'背景色'"></select>
          </span>
        </span>
        <span class="ql-formats">
          <button class="ql-list" value="ordered" type="button" v-tooltip.bottom="'有序列表'"></button>
          <button class="ql-list" value="bullet" type="button" v-tooltip.bottom="'无序列表'"></button>
          <select class="ql-align">
            <option defaultValue></option>
            <option value="center"></option>
            <option value="right"></option>
            <option value="justify"></option>
          </select>
        </span>
        <span class="ql-formats">
          <button class="ql-link" type="button" v-tooltip.bottom="'插入链接'"></button>
        </span>
        <span class="ql-formats">
          <button class="ql-clean" type="button" v-tooltip.bottom="'清除格式'"></button>
        </span>
      </template>
    </Editor>

    <!-- 发布按钮 -->
    <div class="flex justify-end p-2">
      <Button label="发布" @click="onPublish" class="p-button-sm" />
    </div>
  </div>

  <!-- 发布中 -->
  <div
    class="fixed h-screen w-screen left-0 top-0 bg-black bg-opacity-60 z-50 flex flex-col justify-center items-center"
    :class="{ '!hidden': !publishing }"
  >
    <i class="far fa-spinner fa-3x text-white animate-spin"></i>
    <span class="text-white">发布中</span>
  </div>
</template>

<script lang="ts">
export default defineComponent({
  name: 'DesignerCreateWorks',
})
</script>

<script lang="ts" setup>
import { defineComponent, ref } from 'vue'
import { useToast } from 'primevue/usetoast'
import { useRouter } from 'vue-router'
import { uploadImage } from '@/api/user/image'
import { getDictList } from '@/api/admin/dict'
import { publishWorks } from '@/api/designer/designer'

import Button from 'primevue/button'
import CascadeSelect from 'primevue/cascadeselect'
import Editor from 'primevue/editor'
import FileUpload from 'primevue/fileupload'

const props = defineProps<{ id: string }>()
let toast = useToast()
const router = useRouter()

const content = ref<string>()
const imgs = ref<any[]>([])
const imgLinks: Image[] = []
const editor = ref()
const publishing = ref(false)

const commit = ref(false)
const w_material = ref<number>() // 作品面料
const w_clothes = ref<number>() // 作品服装类型
const w_style = ref<number>() // 作品风格

const _w_material = ref<Dict[]>([])
const _w_clothes = ref<Dict[]>([])
const _w_style = ref<Dict[]>([])

function onSelect(e: any) {
  imgs.value = e.files
}

async function onPublish() {
  commit.value = true

  // 判断能否发布
  if (!(w_material.value && w_clothes.value && w_style.value)) {
    toast.add({
      severity: 'error',
      summary: '发布失败',
      detail: '请完成所有必填项',
      life: 3000,
    })
    return
  }
  if (imgs.value.length === 0) {
    toast.add({
      severity: 'error',
      summary: '发布失败',
      detail: '请至少上传一张作品图片',
      life: 3000,
    })
    return
  }
  if (!content.value) {
    toast.add({
      severity: 'error',
      summary: '发布失败',
      detail: '内容不能为空',
      life: 3000,
    })
    return
  }

  // 上传图片
  publishing.value = true
  for (let i = 0; i < imgs.value.length; i++) {
    let formData = new FormData()
    formData.append('picture', imgs.value[i])
    await uploadImage(formData, 30)
      .then(res => {
        imgLinks.push(res.data)
      })
      .catch(err => {
        toast.add({
          severity: 'error',
          summary: '发布失败',
          detail: `图片上传失败，${err.data.msg}`,
          life: 3000,
        })
        return
      })
  }

  // 发布作品
  publishWorks(props.id, {
    style: {
      did: w_style.value,
    },
    imgs: imgLinks,
    fabric: {
      did: w_material.value,
    },
    clothType: {
      did: w_clothes.value,
    },
    description: content.value,
  })
    .then(res => {
      toast.add({
        severity: 'success',
        summary: '发布成功',
        detail: '正在跳转',
        life: 3000,
      })
      setTimeout(() => {
        router.push({ path: `/designer/works/${res.data}` })
      }, 1000)
      publishing.value = false
    })
    .catch(err => {
      toast.add({
        severity: 'error',
        summary: '发布失败',
        detail: err.data.msg,
        life: 3000,
      })
      imgLinks.length = 0
      publishing.value = false
    })
}

getDictList(1)
  .then(res => {
    _w_material.value = res.data.list
  })
  .catch(err => {
    toast.add({
      severity: 'error',
      summary: '获取面料分类失败',
      detail: err.data.msg,
      life: 3000,
    })
  })

getDictList(2)
  .then(res => {
    _w_clothes.value = res.data.list
  })
  .catch(err => {
    toast.add({
      severity: 'error',
      summary: '获取服装分类失败',
      detail: err.data.msg,
      life: 3000,
    })
  })

getDictList(11)
  .then(res => {
    _w_style.value = res.data.list
  })
  .catch(err => {
    toast.add({
      severity: 'error',
      summary: '获取风格分类失败',
      detail: err.data.msg,
      life: 3000,
    })
  })
</script>
